home *** CD-ROM | disk | FTP | other *** search
/ FishMarket 1.0 / FishMarket v1.0.iso / fishies / 301-325 / disk_319 / cnewssrc / cnews.orig.lzh / contrib / putenv.alt.c < prev    next >
C/C++ Source or Header  |  1989-06-27  |  1KB  |  58 lines

  1. /*
  2.  * From: chip@ateng.ateng.com (Chip Salzenberg)
  3.  * Newsgroups: comp.unix.wizards
  4.  * Subject: Re: replacement for putenv()
  5.  * Date: 13 Feb 89 16:51:05 GMT
  6.  * 
  7.  * Here is a rather nice replacement for putenv().  I wrote it for the BSD port
  8.  * of my deliver program.  (I know it's source, but it's short.)  Its nicest
  9.  * feature is the avoidance of memory waste when it is called several times.
  10.  */
  11.  
  12. int
  13. putenv(s)
  14. char *s;
  15. {
  16.     static char **env_array;
  17.     static int env_size;
  18.     char *e;
  19.     int i, j;
  20.  
  21.     if (env_array == NULL) {
  22.         for (i = 0; environ[i]; ++i)
  23.             ;
  24.         env_size = i + 10;          /* arbitrary */
  25.         env_array = (char **) malloc(env_size * sizeof(char *));
  26.         if (env_array == NULL)
  27.             return 1;
  28.         memcpy((char *)env_array, (char *)environ,
  29.                (int) ((i + 1) * sizeof(char *)));
  30.         environ = env_array;
  31.     } else if (environ != env_array)
  32.         fprintf(stderr, "putenv: warning: someone moved environ!\n");
  33.  
  34.     if ((e = strchr(s, '=')) != NULL)
  35.         ++e;
  36.     else
  37.         e = s + strlen(s);
  38.  
  39.     j = 0;
  40.     for (i = 0; env_array[i]; ++i)
  41.         if (strncmp(env_array[i], s, e - s) != 0)
  42.             env_array[j++] = env_array[i];
  43.  
  44.     if (j + 1 >= env_size) {
  45.         env_size += 10;                 /* arbitrary */
  46.         env_array = (char **) realloc((char *)env_array,
  47.                     env_size * sizeof(char **));
  48.         if (env_array == NULL)
  49.             return 1;
  50.     }
  51.  
  52.     env_array[j++] = s;
  53.     env_array[j] = NULL;
  54.  
  55.     environ = env_array;
  56.     return 0;
  57. }
  58.